
var win = null;
var cvs = null;
var ctx = null;


function main (evt) {
    win = window;
    cvs = document.getElementById('canvas');
    ctx = cvs.getContext('2d');
    if (!ctx) {
        return;
    }
    cvs.width = W = win.innerWidth;
    cvs.height = H = win.innerHeight;

    var t1 = new Triangle(2, 2);
    // t1.moveTo(300, 300);
    // t1.rotate(45);

    // var t2 = new Triangle(2, 2, '#f60');
    // t2.moveTo(500, 200);
    // t2.rotate(135);
}


function Shap () {
    this.unit = 100;
    this.color = '#69c';
};

Shap.prototype = {
    draw: function (opts) {
        var points = this.points;

        // ctx.save();
        ctx.beginPath();
        if (opts) {
            if (opts.moveTo) {
                console.log('moveTo', opts.moveTo);
                ctx.translate(opts.moveTo.x, opts.moveTo.y);
            }
            if (opts.rotate) {
                console.log('rotate', opts.rotate);
                ctx.rotate(opts.rotate);
            }
        }

        
        
        ctx.moveTo(points[0].x, points[0].y);
        for (var i = 1; i < points.length; i++) {
            ctx.lineTo(points[i].x, points[i].y);
        }
        ctx.closePath();
        ctx.fillStyle = this.color;
        // ctx.restore();

        ctx.fill();
    },

    moveTo: function (x, y) {
        this.clear();
        this.draw({
            moveTo: { x: x, y: y}
        });
    },

    rotate: function (deg) {
        deg = deg / 180 * Math.PI;
        this.clear();
        this.draw({
            rotate: deg
        });
    },

    clear: function () {
        console.log('clear', this.points[0].x, this.points[0].y, this.width, this.height);
        ctx.clearRect(this.points[0].x, this.points[0].y, this.width, this.height);
    }
};


function Triangle (width, height, color) {
    this.init(width, height, color);
}

Triangle.prototype = new Shap();

Triangle.prototype.init = function (width, height, color) {
    this.width = this.unit * width;
    this.height = this.unit * height;
    this.color = color || this.color;
    this.points = [
        { x: 0, y: 0 },
        { x: this.width, y: 0 },
        { x: this.width, y: this.height }
    ];
    this.draw();
};



window.addEventListener('load', main);